var express = require('express');
//文档模型
const UserModel = require('../../model/UserModel');
//导入中间件
const checkTokenMiddleWare = require('../../MiddleWares/checkTokenMiddleWare')
const resultResponeMiddleWare = require('../../MiddleWares/resultResponeMiddleWare')
var router = express.Router();
//加密包
var md5 = require('md5');
//导入配置对象
const config = require('../../config/config');
//token包
const jwt = require('jsonwebtoken')
const { secret } = require('../../config/config');

//校验包
// 导入 @escook/express-joi
const expressJoi = require('@escook/express-joi')
//导入验证对象
const reg_log_schema = require('../../schema/reg_log');



/* 注册 */
// router.post('/reg', expressJoi(reg_log_schema),resultResponeMiddleWare, function (req, res, next) {
//   let { username, password } = req.body
//   // if (!username || !password) {
//   //   res.json({code:1, message:"注册失败,用户名密码不能为空"})
//   // }
//   UserModel.findOne({ username }).then(data => {
//     if (data) {
//       res.json({code:1, message:"注册失败"})
//     } else {
//       UserModel.create({ username, password: md5(password) }).then(data => {
//         res.json({code:0, message:"注册成功"})
//       }).catch(err => {
//         res.json({ code:1,message:"注册失败"})
//       })
//     }
//   }).catch(err => {
//     console.log(err);
//   })
// });
router.post('/reg', resultResponeMiddleWare, function (req, res, next) {
  let { username, password } = req.body
  if (!username || !password) {
    res.sendResponse(123, "用户名或者密码不能为空", null)
  }
  UserModel.findOne({ username }).then(data => {
    if (data) {
      res.sendResponse(123, "注册失败,用户名已存在", null)
    } else {
      UserModel.create({ username, password: md5(password) }).then(data => {
        res.sendResponse()
      }).catch(err => {
        res.sendResponse(1, "注册失败")
      })
    }
  }).catch(err => {
    console.log(err);
  })
});

/* 登录 */
router.post('/login', resultResponeMiddleWare, function (req, res, next) {
  let { username, password } = req.body
  if (!username || !password) {
    res.sendResponse(123, "用户名或者密码不能为空", null)
  }
  UserModel.findOne({ username, password: md5(password) }).then(data => {
    let id = data._id.toString()
    // sign(用户数据，加密字符串，配置对象)
    let token = jwt.sign({
      username: data.username,
      id: id
    },
      secret, {
      expiresIn: config.expiredIn
    })
    // if (data.password === md5(password)){
    res.sendResponse(0, "登陆成功", "Bearer " + token)
  }).catch(err => {
    res.sendResponse(345, "登陆失败，用户名或密码错误", null)
  })
});



module.exports = router;
